
import React, { useEffect, useState } from "react";
import styles from "./pagination.module.scss";
const XvPagination = ({
    defaultCurrent = 1,
    total = 51,
    defaultPageSize = 10,
    current = 1,
    onChange = Function
}) => {
    const [totalPage, setTotalPage] = useState(0);
    const [currentPage, setCurrentPage] = useState(defaultCurrent);

    useEffect(() => {
        let totlaPage = 0;
        let m = Number(total) % Number(defaultPageSize);
        totlaPage = Math.floor(Number(total) / Number(defaultPageSize));
        if (m > 0) {
            totlaPage = Number(totlaPage) + 1;
        }
        setTotalPage(totlaPage)
    }, [total, defaultPageSize])

    // 失焦 去查找 
    const inputFocus = () => {
        onChange(currentPage);
    }

    const inputChange = (e) => {
        setCurrentPage(e.target.value)
    }

    // 自增或自减
    const changePage = (type = 1) => {
        let current = currentPage;

        if (type === 1) {
            current++;
        } else {
            current--
        }
        if (current < 1 || current > totalPage) {
            return false;
        }
        setCurrentPage(current);
        onChange(current);
    }

    useEffect(()=>{
        setCurrentPage(current);
    },[current])

    return (
        <>
            <div className={styles.styles}>
                <div className="content">
                    <div
                        onClick={() => changePage(0)}
                        className="iconfont left-icon">
                        &#xe623;
                    </div>
                    <div className="currentPage">
                        <input className="input"
                            onFocus={inputFocus}
                            onChange={inputChange}
                            value={currentPage} type="number" name="" id="" />
                    </div>
                    <div className="icon">/</div>
                    <div className="totalPage">{totalPage}</div>
                    <div
                        onClick={() => changePage(1)}
                        className="iconfont right-icon">
                        &#xe658;
                    </div>
                </div>
            </div>
        </>
    )
}
export default XvPagination;